import React, { Component } from 'react';
import { StyleSheet, Text, View, Dimensions, TouchableOpacity, Image,
  ScrollView, DeviceEventEmitter, Alert } from 'react-native';
import { List, ListItem, Card, CardItem, Right, Left } from 'native-base';
import theme from '../../../native-base-theme/variables';
import * as incidentRequest from '../../../services/incidentRequest';
import { produce } from 'immer';
import { UtilToast } from '../../../utils/util-method';
import ZlstIcon from '../../../components/zlst-icons';

class changeParts extends Component {
  static navigationOptions = {
    title: '零部件更换',
    headerStyle: { backgroundColor: theme.toolbarDefaultBg, borderBottomWidth: 0, elevation: 0 },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  qrcodeList = {};

  // 构造方法
  constructor(props) {
    super(props);
    this.state = {
      isError: false,
      listData: {},
      loctionArry: [],
      moreChoice: false,
    };
  }


  // 初始化方法
  componentDidMount() {
    DeviceEventEmitter.addListener('changpageQuery', this.queryData);
    if (this.props.navigation) {
      // console.log('参数', this.props.navigation.state.params);
      this.qrcodeList = this.props.navigation.state.params;
      this.queryData();
    }
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('changpageQuery');
  }

  // 查询数据 getFindMmMaterialVo
  queryData = async () => {
    const ajaxData = {
      lotCode: this.qrcodeList.code,
    };
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const list = await incidentRequest.getFindMmMaterialVo(ajaxData);
      if (list.data) {
        this.setState(produce(draft => {
          if (list.resultCode === 0 && list.data !== null) {
            DeviceEventEmitter.emit('showLoading', false);
            draft.listData = list.data;
            this.queryLoction(list.data.lotCode);
          }
        }));
        /**
         * 如果状态=6，需提示：此备件为换下件，是否换上？
         * 如果点击确定，进入零部件更换界面，如果点击取消，返回扫描二维码页面
         */
        if (this.state.listData.lotStatus == 6) {
          Alert.alert(
            '提示',
            '此备件为换下件，是否换上',
            [
              {
                text: '取消',
                style: 'cancel',
                onPress: () => {
                  this.props.navigation.navigate({ routeName: 'Qrcode', params: { flag: 'part', equipObjType: this.props.navigation.state.params.equipObjType, equipmentId: this.props.navigation.state.params.equipmentId } });
                },
              },
              {
                text: '确定',
              },
            ],
          );
        }
      } else {
        UtilToast('扫出的条码号没有对应的备件信息', 'danger');
        DeviceEventEmitter.emit('showLoading', false);
        this.props.navigation.goBack();
      }
      // console.log('===', list.data);
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  // 拆分位置查询 getFindPositionInfo
  queryLoction = async (vl) => {
    const ajaxData = {
      equipmentId: this.qrcodeList.equipmentId,
      lotCode: vl,
      objType: this.qrcodeList.equipObjType,
      // objType: 'RX_200DLX',
      // equipmentId: '402892e4675e4e5f01675e8d470c03f5',
      // lotCode: '170400003486RX201812050001',
      // objType: 'RX_200ZLJZ',
    };
    try {
      const mlist = await incidentRequest.getFindPositionInfo(ajaxData);
      const list = mlist.data.map(it => ({
        ...it,
        checked: false,
      }));
      // console.log('拆分数据', list.data);
      this.setState(produce(draft => {
        if (mlist.resultCode === 0) {
          draft.loctionArry = list;
        }
      }));
    } catch (error) {
      this.setState({ isError: false });
    }
  }

  // 选择位置
  listClick = (item, index) => {
    // console.log('item', item);
    // let list = [];
    if (this.state.moreChoice === false) { // 单选
      if (item) {
        const params = {
          downPart: {
            lotCode: item.lotCode,
            materialId: item.materialId,
            materialName: item.materialName,
            splitCode: item.splitCode,
            splitItemId: item.splitItemId,
            description: item.description,
          },
          upPart: this.state.listData,
          equipmentId: this.qrcodeList.equipmentId,
          equipObjType: this.qrcodeList.equipObjType,
        };
        this.props.navigation.goBack();
        this.props.navigation.navigate({ routeName: 'changePartsConfirm', params });
      }
    } else { // 多选
      this.setState(produce(draft => {
        draft.loctionArry[index].checked = !draft.loctionArry[index].checked;
      }));
    }
  };

  // 显示图片
  _showDetaiImage = (item) => {
    // console.log('URL====', incidentRequest.getDownloadImg);
    if (item.photos) {
      return {
        uri: `${incidentRequest.getDownloadImg}/${item.photos}?token=${global.__TOKEN_ACCESS__}`,
      };
    }
    return require('../../../../assets/images/no-pic.png');
  }

  _getPage = () => {
    const list = [];
    let key = 0;
    const { loctionArry } = this.state;
    loctionArry.forEach((item, index) => {
      list.push(
        <ListItem key={key} onPress={() => this.listClick(item, index)}>
          {this.state.moreChoice && (
            <ZlstIcon
              style={{ color: item.checked ? '#207aff' : 'white', marginRight: 8 }}
              name="gouxuan"
              size={this.size}
            />
          )}
          <Text style={{ color: '#ffffff' }}>
            {item.splitItemType == '0' && (
              <Text style={{ color: 'red' }}>
                (临)
              </Text>
            )}
            {item.description}@{item.materialName}
          </Text>
        </ListItem>,
      );
      key += 1;
    });
    return list;
  }

  moreChoice = () => {
    this.setState(produce(draft => {
      draft.moreChoice = !draft.moreChoice;
    }));
  }

  _refresh = () => {
    this.queryLoction(this.qrcodeList.code);
  }

  addPosition = () => {
    const params = {
      upPart: this.state.listData,
      equipmentId: this.qrcodeList.equipmentId,
      equipObjType: this.qrcodeList.equipObjType,
      _refresh: this._refresh,
    };
    this.props.navigation.navigate({ routeName: 'AddPosition', params });
  }

  sureChoice = () => {
    const list = this.state.loctionArry.filter((it) => (it.checked));
    if (list && list.length > 0) {
      // if (list.length <= this.state.listData.usableQty) {
      // if (true) {
      Alert.alert(
        '提示',
        '确定选择吗',
        [
          { text: '取消', style: 'cancel' },
          {
            text: '确定',
            onPress: () => {
              this.sure(list);
            },
          },
        ],
      );
      // } else {
      //   UtilToast('选择位置不能大于库存数目', 'danger');
      // }
    } else {
      UtilToast('请至少选择一个位置', 'danger');
    }
  }

  sure = (downParts) => {
    const upParts = [];
    upParts.push(this.state.listData);
    const params = {
      upParts,
      downParts,
      downPart: {
        lotCode: downParts[0].lotCode,
        materialId: downParts[0].materialId,
        materialName: downParts[0].materialName,
        splitCode: downParts[0].splitCode,
        splitItemId: downParts[0].splitItemId,
        description: downParts[0].description,
      },
      upPart: this.state.listData,
      equipmentId: this.qrcodeList.equipmentId,
      equipObjType: this.qrcodeList.equipObjType,
    };
    this.props.navigation.goBack();
    this.props.navigation.navigate({ routeName: 'changePartsMoreConfirm', params });
  }

  render() {
    const { listData } = this.state;
    return (
      <View style={styles.container}>
        <ScrollView>
          <Card>
            <CardItem cardBody>
              <Image source={this._showDetaiImage(listData)} style={{ height: 200, width: null, flex: 1 }} />
            </CardItem>
          </Card>
          <View style={styles.header}>
            <View style={{ flex: 1 }}>
              <Text>基本信息</Text>
            </View>
            {/* <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-end' }}>
              <TouchableOpacity onPress={() => this.addPosition()}>
                <Text style={{ paddingLeft: 8, paddingRight: 8 }}>新增临时位置</Text>
              </TouchableOpacity>
            </View> */}
          </View>
          <View style={styles.lineItemContent}>
            <View style={styles.itemLeft}>
              <Text style={styles.leftFontStyle}>编码</Text>
              <Text style={styles.leftFontStyle}>名称</Text>
              <Text style={styles.leftFontStyle}>型号</Text>
              <Text style={styles.leftFontStyle}>供应商</Text>
              <Text style={styles.leftFontStyle}>生产厂商</Text>
              <Text style={styles.leftFontStyle}>入库日期</Text>
              <Text style={styles.leftFontStyle}>出库日期</Text>
              {/* <Text style={styles.leftFontStyle}>库存</Text> */}
              {/* <Text style={styles.leftFontStyle}>位置</Text> */}
            </View>
            <View style={styles.itemRight}>
              <Text style={styles.rightFontStyle}>{listData.lotCode}</Text>
              <Text style={styles.rightFontStyle}>{listData.materialName}</Text>
              <Text style={styles.rightFontStyle}>{listData.materialSpecModel}</Text>
              <Text style={styles.rightFontStyle}>{listData.supplierName}</Text>
              <Text style={styles.rightFontStyle}>{listData.manufacturerName}</Text>
              <Text style={styles.rightFontStyle}>{listData.inDate}</Text>
              <Text style={styles.rightFontStyle}>{listData.outDate}</Text>
              {/* <Text style={styles.rightFontStyle}>{listData.usableQty}</Text> */}
              {/* <Text style={styles.rightFontStyle}>{this.location}</Text> */}
            </View>
          </View>
          <View style={styles.header}>
            <View style={{ flex: 1 }}>
              <Text>请选择位置</Text>
            </View>
            <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-end' }}>
              {
                this.state.moreChoice === false ? (
                  <TouchableOpacity onPress={() => this.moreChoice()}>
                    <Text style={{ paddingLeft: 8, paddingRight: 8 }}>批量选择</Text>
                  </TouchableOpacity>
                ) : (
                  <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'flex-end' }}>
                    <TouchableOpacity onPress={() => this.moreChoice()}>
                      <Text style={{ paddingLeft: 8, paddingRight: 8 }}>取消</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={() => this.sureChoice()}>
                      <Text style={{ paddingLeft: 8, paddingRight: 8 }}>确定</Text>
                    </TouchableOpacity>
                  </View>
                )
              }
            </View>
          </View>
          <View>
            <List>
              {this._getPage()}
            </List>
            <View style={{ flex: 1 }}>
              <TouchableOpacity onPress={() => this.addPosition()}>
                <Text style={{ padding: 16, color: 'white' }}>
                  {this.state.loctionArry.length === 0 ? '该设备暂时没有位置可安装此备件，请确认备件是否正确。或' : '未找到正确位置，'}
                  <Text style={{ color: '#207aff' }}>
                    新增临时位置
                  </Text>
                </Text>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </View>
    );
  }
}
const deviceWidth = Dimensions.get('window').width;
const styles = StyleSheet.create({
  container: {
    // width: '100%',
    flex: 1,
    backgroundColor: theme.myPrimary,
  },
  lineItemContent: { // 保证子元素在同一行
    // display: 'flex',
    flexDirection: 'row',
    flexWrap: 'nowrap',
    paddingTop: 5,
    paddingBottom: 5,
    backgroundColor: theme.myPrimary,
    paddingLeft: 18,
  },
  itemLeft: {
    width: deviceWidth * 0.3,
  },
  leftFontStyle: {
    color: '#ffffff',
    fontSize: 16,
    marginTop: 6,
  },
  itemRight: {
    width: deviceWidth * 0.7,
  },
  rightFontStyle: {
    color: '#dbdbdb',
    fontSize: 16,
    marginTop: 6,
  },
  header: {
    flexDirection: 'row',
    backgroundColor: '#ffffff',
    borderLeftWidth: 8,
    borderLeftColor: '#4f6fe3',
    borderStyle: 'solid',
    padding: 10,
    fontSize: 17,
    fontFamily: 'PingFangHK-Regular',
  },
});

export default changeParts;
